import React from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import ZbSchulteGame from '@/comps/schulte';
import ZbSeparator from '@/comps/common/Separator';
import { AtButton } from 'taro-ui';
import { useLocalStore } from 'mobx-react';
import authStore from '@/store/auth';
import RankApi from '@/api/rank';
import { COMMON_CONFIG, RANK } from '@/app.contants';
import Routes from '@/utils/route';
import ZbLogin from '@/comps/login';

import './index.scss';

const SchulteContent = () => {
  const router = Taro.useRouter();
  const localAuth = useLocalStore(() => authStore);

  const [score, setScore] = React.useState<number>(0);

  const [isLogin, setIsLogin] = React.useState<boolean>(false);

  // 分享
  Taro.useShareAppMessage((res) => {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: '舒尔特方格，看看你能多少秒完成？',
      path: 'pages/schulte/index',
    };
  });

  const [level, setLevel] = React.useState<number>(3);

  React.useEffect(() => {
    if (router.params.level) {
      setLevel(parseInt(router.params.level));
    }
  }, [router.params.level]);

  // 获取成绩
  const getSchulteScore = (score: number) => {
    console.log('获取成绩', score);
    setScore(score);
  };

  // 保存成果
  const onSaveScore = async () => {
    // 判断用户有没有登陆
    if (!localAuth.check()) {
      setIsLogin(true);
      return;
    }
    const param = {
      score,
      type: RANK.SCHULTE,
      level,
      userId: localAuth.user.id,
    };
    const res = await RankApi.saveScore(param);
    if (res.code === COMMON_CONFIG.SUCCESS) {
      Routes.navigateBack();
    }
  };

  // 关闭登录弹框的回调
  const onLoginClose = () => {
    setIsLogin(false);
  };

  return (
    <View className="p-2">
      <ZbSchulteGame key={level} columnNum={level} onChange={getSchulteScore}>
        <ZbSeparator bgColor="#F5F3FF" />
        <View className="p-1">
          <AtButton type="primary" onClick={onSaveScore}>
            保存结果
          </AtButton>
        </View>
        <View className="p-1">
          <AtButton type="secondary" openType="share">
            去分享
          </AtButton>
        </View>
      </ZbSchulteGame>
      <ZbLogin authStore={localAuth} isShow={isLogin} onClose={onLoginClose} />
    </View>
  );
};

export default SchulteContent;
